<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var    数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}



//父id查询分类下所有子id
function getUpTreeold($array,$pid=0,$leave = 0){
    $f_name = __FUNCTION__;
    static $list = [];
    foreach ($array as $key => $value){
        if ($value['pid'] == $pid){
            $value['leave'] = $leave;
            $bq = str_repeat('|--',$value['leave']);
            echo $bq.$value['n'].$leave.'<br>';
            $list[] = $value;
            unset($array[$key]);
            $f_name($array,$value['id'],$leave+1);
        }
    }
    return $list;
}
//父id查询分类下所有子id 以及自己
function getUpTree($array,$pid=0){
    $f_name = __FUNCTION__;
    static $list = [];
    foreach ($array as $key => $value){
        if ($value['pid'] == $pid){
            unset($value['pid']);
            $list[] = $value;
            $f_name($array,$value['id']);
        }
    }

    $retlist = [];
    if($list){
        foreach ($list as $v){
            $retlist[] = $v['id'];
        }
    }

    array_push($retlist,$pid);

    return $retlist;
}


//指定数组以$keys键值排序 不显示 键的下标
function array_sort($array,$keys,$type='asc'){
//$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
    $keysvalue = $new_array = array();
    foreach ($array as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[] = $array[$k];
    }
    return $new_array;
}


//指定数组以$keys键值排序
function array_sort2($array,$keys,$type='asc'){
//$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
    $keysvalue = $new_array = array();
    foreach ($array as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $array[$k];
    }
    return $new_array;
}

//GCJ-02(火星，高德)坐标转换成BD-09(百度)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_encrypt($gg_lon,$gg_lat){
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $gg_lon;
    $y = $gg_lat;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $bd_lon = $z * cos($theta) + 0.0065;
    $bd_lat = $z * sin($theta) + 0.006;
    // 保留小数点后六位
    $data['bd_lon'] = round($bd_lon, 6);
    $data['bd_lat'] = round($bd_lat, 6);
    return $data;
}


//BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_decrypt($bd_lon,$bd_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $bd_lon - 0.0065;
    $y = $bd_lat - 0.006;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    // $data['gg_lon'] = $z * cos($theta);
    // $data['gg_lat'] = $z * sin($theta);
    $gg_lon = $z * cos($theta);
    $gg_lat = $z * sin($theta);
    // 保留小数点后六位
    $data['gg_lon'] = round($gg_lon, 6);
    $data['gg_lat'] = round($gg_lat, 6);
    return $data;
}


//BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度
function jwdchange($bd_lon,$bd_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $bd_lon - 0.0065;
    $y = $bd_lat - 0.006;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    // $data['gg_lon'] = $z * cos($theta);
    // $data['gg_lat'] = $z * sin($theta);
    $gg_lon = $z * cos($theta);
    $gg_lat = $z * sin($theta);
    // 保留小数点后六位
    $data['gg_lon'] = round($gg_lon, 6);
    $data['gg_lat'] = round($gg_lat, 6);
    return $data;
}

//判断字符串在另一个字符串中出现的次数
function check_str($str, $substr)
{
    $nums=substr_count($str,$substr);
    if ($nums>1)
    {
        return 2;
    }
    elseif($nums == 1)
    {
        return 1;
    }else{
        return 0;
    }
}

//校验日期
function check_date($data){
    $datestr = explode("/",$data);
    if(count($datestr) != 3){
         return 0;
    }else{
        if(checkdate($datestr[0],$datestr[1],$datestr[2])){
            return 1;
        }else{
            return 0;
        }

    }

}

//判断两个日期相差的月份
function diffDate($date1,$date2)
{
    $datetime1 = new \DateTime($date1);
    $datetime2 = new \DateTime($date2);
    $interval = $datetime1->diff($datetime2);
    $time['y']         = $interval->format('%Y');
    $time['m']         = $interval->format('%m');
    $time['d']         = $interval->format('%d');
    $time['h']         = $interval->format('%H');
    $time['i']         = $interval->format('%i');
    $time['s']         = $interval->format('%s');
    $time['a']         = $interval->format('%a');    // 两个时间相差总天数
    return $time;
}

//替换富文本图片为绝对路径
function pregReplaceImg2($content,$prefix)
{
    $contentAlter = preg_replace_callback('/(<[img|IMG].*?src=[\'\"])([\s\S]*?)([\'\"])[\s\S]*?/i', function($match)use($prefix){
        if(strstr($match[2], 'http://') == false && strstr($match[1], 'https://') == false)
            return $match[1].$prefix.$match[2].$match[3];
        else
            return $match[1].$match[2].$match[3];
    } , $content);
    return $contentAlter;
}

function subText3($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 0, $length, 'utf8') . '...';
    } else {
        return $text;
    }
}

//获取目录下所有文件，包括子目录
function get_allfiles($path,&$files)
{
    if(is_dir($path))
    {
        $dp = dir($path);
        while ($file = $dp ->read())
        {
            if($file !== "." && $file !== "..")
            {
                get_allfiles($path."/".$file, $files);
            }
        }
        $dp ->close();
    }
    if(is_file($path))
    {
        //过滤 xls xlsx
        if(get_extension($path) == "xls" || get_extension($path) == "xlsx"){

        }else{
            //根据不同文件名称进行分组 考虑多个项目图片和视频放到对应的项目名称文件夹下
            $var = explode("/",$path);
            $key = $var[2];
            //将图片和视频分开
            if(get_extension($path) == "jpg"){
                $files[$key]['jpg'][] =  $path;
            }else{
                $files[$key]['mp4'][] =  $path;
            }

        }

    }

    return $files;
}

//获取文件后缀
function get_extension($file)
{
    return pathinfo($file, PATHINFO_EXTENSION);
}


//获取某个目录下所有的目录（包括子目录，子孙目录）和文件，直到最里层
function getDir2($path){

    if(is_dir($path)){

        $dir = scandir($path);
        foreach ($dir as $value){
            $sub_path =$path .'/'.$value;
            if($value == '.' || $value == '..'){
                continue;
            }else if(is_dir($sub_path)){
                echo '目录名:'.$value .'<br/>';
                getDir($sub_path);
            }else{
                //.$path 可以省略，直接输出文件名
                echo ' 最底层文件: '.$path. ':'.$value.' <hr/>';
            }
        }
    }
}


function searchDir($path,&$files){

    if(is_dir($path)){

        $opendir = opendir($path);

        while ($file = readdir($opendir)){
            if($file != '.' && $file != '..'){
                searchDir($path.'/'.$file, $files);
            }
        }
        closedir($opendir);
    }
    if(!is_dir($path)){
        $files[] = $path;
    }
}



//获取某目录下所有子文件和子目录
function getDirContent($path){
    if(!is_dir($path)){
        return false;
    }
    $arr = array();
    $data = scandir($path);
    foreach ($data as $value){
        if($value != '.' && $value != '..'){
            $arr[] = $value;
        }
    }
    return $arr;
}



//动态计算当前年的开始和结束日期 返回开始和完成日期
function comhbdate($sdate,$edate){
    $ysdate = date("Y",strtotime($sdate));
    $yedate = date("Y",strtotime($edate));
    $nowyear = date("Y",time());
    $nowmonth = date("m",time());

    //开始日期和当前日期 比较
    if($ysdate < $nowyear){
        $psdate = $nowyear."-01";
    }else{
        $psdate = $sdate;
    }
    $dmonth = date("m",strtotime($psdate));


    //结束日期余额当前日期 比较
    if($yedate > $nowyear){
        $pedate = $nowyear."-12";
    }else{
        $pedate = $edate;
    }
    $arr['sdate'] = $psdate;
    $arr['edate'] = $pedate;
    $arr['percent'] = comPercent($psdate,$pedate);

    //截止到汇报时，计算应该累计的汇报比例
    $count = hbCount($dmonth,$nowmonth);
    $arr['itempecent'] = $count * $arr['percent'];
    return $arr;
}

//动态计算单个汇报时的年度次数比例数据 返回比例
function comPercent($sdate,$edate){
        $dmonth = date("m",strtotime($sdate));
        $emonth = date("m",strtotime($edate));
        $ysdate = date("Y",strtotime($sdate));
        $nowyear = date("Y",time());
        if($ysdate == $nowyear){
            $percent = hbPercent($dmonth,$emonth);
        }
        if($ysdate < $nowyear){
            $percent = 1;
        }
        if($ysdate > $nowyear){
            $percent = 0;
        }
        return $percent;
}
//指定月份动态计算汇报次数 返回百分比
function hbPercent($smonth,$emonth){
      $intsmonth = (int)$smonth;
      //根据双月逻辑，如果是偶数月 按照奇数月计算 开始月 减一
      if($intsmonth%2 == 0){
          $intsmonth = $intsmonth-1;
      }
    //根据双月逻辑，如果是奇数月 按照偶数月计算 结束月 加一
      $intemonth = (int)$emonth;
      if($intemonth%2 == 1){
          $intemonth = $intemonth+1;
      }
      //指定年度应该上报的次数
      $allcount = ceil(($intemonth - $intsmonth)/2);
     // $ypercent = sprintf("%01.2f", 1/$allcount);
      $ypercent =  1/$allcount;
      //不进行 四舍五入
      $ypercent = substr(sprintf("%.3f",$ypercent),0,-1);
      ////转换为百分比
      //$ypercent = ($ypercent * 100) ."%";
      return $ypercent;
}
//截止到目前月应该汇报的总次数 返回次数
function hbCount($smonth,$emonth){
    $intsmonth = (int)$smonth;
    //根据双月逻辑，如果是偶数月 按照奇数月计算 开始月 减一
    if($intsmonth%2 == 0){
        $intsmonth = $intsmonth-1;
    }
    //根据双月逻辑，如果是奇数月 按照偶数月计算 结束月 加一
    $intemonth = (int)$emonth;
    if($intemonth%2 == 1){
        $intemonth = $intemonth+1;
    }
    //指定年度应该上报的次数
    $allcount = ceil(($intemonth - $intsmonth)/2);
    return $allcount;

}